package com.dhl.cloud.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 *
 * @author dhl
 */
public class UtilTools {

	public static int[] shuffle(int size) {
		int[] arr = new int[size];
		for (int i = 0; i < size; i++) {
			arr[i] = i;
		}
		int[] arr2 = new int[size];
		int count = arr.length;
		int cbRandCount = 0;// 索引
		int cbPosition = 0;// 位置
		int k = 0;
		do {
			Random rand = new Random();
			int r = count - cbRandCount;
			cbPosition = rand.nextInt(r);
			arr2[k++] = arr[cbPosition];
			cbRandCount++;
			arr[cbPosition] = arr[r - 1];// 将最后一位数值赋值给已经被使用的cbPosition
		} while (cbRandCount < count);
		return arr2;
	}

	public static int[] shuffle(int[] arr) {
		int[] arr2 = new int[arr.length];
		int count = arr.length;
		int cbRandCount = 0;// 索引
		int cbPosition = 0;// 位置
		int k = 0;
		do {
			Random rand = new Random();
			int r = count - cbRandCount;
			cbPosition = rand.nextInt(r);
			arr2[k++] = arr[cbPosition];
			cbRandCount++;
			arr[cbPosition] = arr[r - 1];// 将最后一位数值赋值给已经被使用的cbPosition
		} while (cbRandCount < count);
		return arr2;
	}

	/**
	 * 去除小数点后面的0
	 * 
	 * @param str
	 * @return
	 */
//	public static String removeZero(String str) {
//		if (org.apache.commons.lang3.StringUtils.isNotBlank(str)) {
//			BigDecimal value = new BigDecimal(str);
//			BigDecimal noZeros = value.stripTrailingZeros();
//			return noZeros.toPlainString();
//		} else {
//			return str;
//		}
//	}

	/**
	 * 26个英文字母转成数字
	 * 
	 * @param character
	 * @return
	 */
	public static String convertChar(String character) {
		return String.valueOf(character.toUpperCase().hashCode() - 64);
	}

	/**
	 * 删除单个文件
	 * 
	 * @param delpath
	 *            String
	 * @return boolean
	 */
	public static boolean deletefile(String filename) {
		boolean flag = false;
		File file = new File(filename);
		if (file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

	// 生成tar并压缩成tar.gz
//	public static void WriteToTarGzip(String rootPath, String folderPath,
//			String targzipFilePath) {
//		byte[] buf = new byte[1024]; // 设定读入缓冲区尺寸
//		try {
//			targzipFilePath = rootPath + targzipFilePath;
//			// 建立压缩文件输出流
//			FileOutputStream fout = new FileOutputStream(targzipFilePath);
//			// 建立tar压缩输出流
//			TarOutputStream tout = new TarOutputStream(fout);
//			tout.setLongFileMode(TarOutputStream.LONGFILE_GNU);
//			addFiles(rootPath, tout, folderPath);
//			tout.close();
//			fout.close();
//
//			// 建立压缩文件输出流
//			FileOutputStream gzFile = new FileOutputStream(targzipFilePath + ".gz");
//			// 建立gzip压缩输出流
//			GZIPOutputStream gzout = new GZIPOutputStream(gzFile);
//			// 打开需压缩文件作为文件输入流
//			FileInputStream tarin = new FileInputStream(targzipFilePath); // targzipFilePath是文件全路径
//			int len;
//			while ((len = tarin.read(buf)) != -1) {
//				gzout.write(buf, 0, len);
//			}
//			gzout.close();
//			gzFile.close();
//			tarin.close();
//
//		} catch (FileNotFoundException e) {
//			System.out.println(e);
//		} catch (IOException e) {
//			System.out.println(e);
//		}
//
//		File tarfile = new File(targzipFilePath);
//		tarfile.delete();
//	}
	
	//判断总共对了多少关键词
		public static int matchesCounts(String useranswer,String[] regex) {
			//初始关键词、默认是0
			int istrue = 0;
			//如果没有判分规则，返回0
			if (regex == null || "".equals(regex)) {
				return istrue;
			}
			for (String str : regex) {
				String[] strs = str.split(",");
				int lens = strs.length;
				if (lens > 1) {
					for (String stres : strs) {
						int index = useranswer.indexOf(stres);
						if (index != -1) {
							useranswer = useranswer.substring(index	+ stres.length());
							istrue++;
							break;
						}
					}
				} 
				else 
				{
					int index = useranswer.indexOf(str);
					if (index != -1) {
						useranswer = useranswer.substring(index + str.length());
						istrue++;
					}
				}
			}
			return istrue;
		}
		
	//修改判分规则中出现空格和单引号'hw_disk_bus'
	public static String getTextFromHtml(String htmlStr) {
		htmlStr = delHTMLTag(htmlStr);
		htmlStr = htmlStr.replaceAll("&nbsp;", " ");
		htmlStr = htmlStr.replaceAll("&#39;", "'");
		// htmlStr = htmlStr.substring(0, htmlStr.indexOf("。")+1);
		return htmlStr;
	}
	private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
	private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
	private static final String regEx_o = "<!--.*?-->";// "<\\!--.*-->";//html注释
	private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
	private static final String regEx_htmlIMG = "<(?!img)[^>]*>"; // 定义HTML标签的正则表达式
																	// (不包含img)
	// private static final String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符
	private static final String regEx_br = "<\\/br>";
	private static String delHTMLTag(String htmlStr) {
		Pattern p_script = Pattern.compile(regEx_script,
				Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern
				.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_o = Pattern.compile(regEx_o, Pattern.CASE_INSENSITIVE);
		Matcher m_o = p_o.matcher(htmlStr);
		htmlStr = m_o.replaceAll("");

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签

		// Pattern p_space = Pattern.compile(regEx_space,
		// Pattern.CASE_INSENSITIVE);
		// Matcher m_space = p_space.matcher(htmlStr);
		// htmlStr = m_space.replaceAll(""); // 过滤空格回车标签
		return htmlStr.trim(); // 返回文本字符串
	}
	// 循环遍历目录结构中的文件并添加至tar的输出流
//		public static void addFiles(String rootPath, TarOutputStream tout,
//				String folderPath) {
//			File srcPath = new File(rootPath + folderPath);
//			int length = srcPath.listFiles().length;
//			byte[] buf = new byte[1024]; // 设定读入缓冲区尺寸
//			File[] files = srcPath.listFiles();
//			try {
//				for (int i = 0; i < length; i++) {
//					if (files[i].isFile()) {
//						System.out.println("file:" + files[i].getName());
//						String filename = srcPath.getPath() + File.separator
//								+ files[i].getName();
//						// 打开需压缩文件作为文件输入流
//						FileInputStream fin = new FileInputStream(filename); // filename是文件全路径
//						TarEntry tarEn = new TarEntry(files[i]); // 此处必须使用new
//																	// TarEntry(File
//																	// file);
//						tarEn.setName(folderPath + File.separator
//								+ files[i].getName()); // 此处需重置名称，默认是带全路径的，否则打包后会带全路径
//						tout.putNextEntry(tarEn);
//						int num;
//						while ((num = fin.read(buf)) != -1) {
//							tout.write(buf, 0, num);
//						}
//						tout.closeEntry();
//						fin.close();
//					} else {
//						System.out.println(files[i].getPath());
//						addFiles(rootPath, tout, folderPath + File.separator
//								+ files[i].getName());
//					}
//				}
//			} catch (FileNotFoundException e) {
//				System.out.println(e);
//			} catch (IOException e) {
//				System.out.println(e);
//			}
//
//		}
	
	/**
	 * 复制单个文件
	 * 
	 * @param oldPath
	 *            String 原文件路径 如：c:/fqf.txt
	 * @param newPath
	 *            String 复制后路径 如：f:/fqf.txt
	 * @return boolean
	 */
	public static void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				// int length;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();

		}

	}
	
	public static void Copy(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) {
				InputStream inStream = new FileInputStream(oldPath);
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				// int length;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					// System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			System.out.println("error  ");
			e.printStackTrace();
		}
	}
	
//	public static void unTarGz(File file, String outputDir) throws IOException {
//
//		TarInputStream tarIn = null;
//
//		try {
//
//			tarIn = new TarInputStream(new GZIPInputStream(
//					new BufferedInputStream(new FileInputStream(file))),
//					1024 * 2);
//			createDirectory(outputDir, null);// 创建输出目录
//			TarEntry entry = null;
//
//			while ((entry = tarIn.getNextEntry()) != null) {
//
//				if (entry.isDirectory()) {// 是目录
//					String a = entry.getName();
//					a = a.replace("\\", "/");
//					createDirectory(outputDir, a);// 创建空目录
//
//				} else {// 是文件
//
//					String a = entry.getName();
//					a = a.replace("\\", "/");
//					File tmpFile = new File(outputDir + "/" + a);
//					createDirectory(tmpFile.getParent() + "/", null);// 创建输出目录
//
//					OutputStream out = null;
//
//					try {
//						out = new FileOutputStream(tmpFile);
//
//						int length = 0;
//
//						byte[] b = new byte[2048];
//
//						while ((length = tarIn.read(b)) != -1) {
//							out.write(b, 0, length);
//						}
//
//					} catch (IOException ex) {
//						ex.printStackTrace();
//						throw ex;
//					} finally {
//
//						if (out != null)
//							out.close();
//					}
//
//				}
//			}
//
//		} catch (IOException ex) {
//			ex.printStackTrace();
//			throw new IOException("解压归档文件出现异常", ex);
//		} finally {
//			try {
//				if (tarIn != null) {
//					tarIn.close();
//				}
//			} catch (IOException ex) {
//				ex.printStackTrace();
//				throw new IOException("关闭tarFile出现异常", ex);
//			}
//		}
//
//	}
	
	public static void createDirectory(String outputDir, String subDir) {

		File file = new File(outputDir);
		if (!(subDir == null || subDir.trim().equals(""))) {// 子目录不为空
			file = new File(outputDir + "/" + subDir);
		}
		if (!file.exists()) {
			file.mkdirs();
		}

	}
	
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}
	
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 复制文件夹
    public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
        // 新建目标目录
        (new File(targetDir)).mkdirs();
        // 获取源文件夹当前下的文件或目录
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                // 源文件
                File sourceFile = file[i];
                // 目标文件
                File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
                copyFile2(sourceFile, targetFile);
            }
            if (file[i].isDirectory()) {
                // 准备复制的源文件夹
                String dir1 = sourceDir + "/" + file[i].getName();
                // 准备复制的目标文件夹
                String dir2 = targetDir + "/" + file[i].getName();
                copyDirectiory(dir1, dir2);
            }
        }
    }
    
    
    // 复制文件
       public static void copyFile2(File sourceFile, File targetFile) throws IOException {
           BufferedInputStream inBuff = null;
           BufferedOutputStream outBuff = null;
           try {
               // 新建文件输入流并对它进行缓冲
               inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
               // 新建文件输出流并对它进行缓冲
               outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
               // 缓冲数组
               byte[] b = new byte[1024 * 5];
               int len;
               while ((len = inBuff.read(b)) != -1) {
                   outBuff.write(b, 0, len);
               }
               // 刷新此缓冲的输出流
               outBuff.flush();
           } finally {
               // 关闭流
               if (inBuff != null)
                   inBuff.close();
               if (outBuff != null)
                   outBuff.close();
           }
       }

}
